package com.allwees.support.fileservice.upload;

import com.allwees.core.common.util.UuidUtil;
import com.allwees.support.fileservice.FileException;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 上传文件的内容及描述信息
 *
 * @author yangylsky
 */
@Getter
@Setter
@Slf4j
public class UploadFileInfo {
	/**
	 * 输入流
	 */
	private InputStream inputStream;

	/**
	 * 原始文件名
	 */
	private String originalName;

	/**
	 * 上传后的文件名
	 */
	private String fileName;

	/**
	 * 文件后缀 .jpg,.png 等
	 */
	private String suffix;

	/**
	 * 文件描述
	 */
	private String description;

	private boolean isImage;

	private byte[] bytes;

	public UploadFileInfo(String originalName){
		int idx = originalName.lastIndexOf(".");
		if(idx == -1) {
			throw new FileException("上传的文件名错误[扩展名为空]: " + originalName);
		}
		this.originalName = originalName;
		this.suffix = originalName.substring(idx);
		this.fileName = UuidUtil.generate() + suffix;
	}

	public UploadFileInfo(InputStream inputStream, String originalName) {
		this(originalName);
		this.inputStream = inputStream;

	}

	public UploadFileInfo(InputStream inputStream, String originalName, String description, boolean isImage) {
		this(inputStream, originalName);
		this.description = description;
		this.isImage = isImage;
	}


	public byte[] getBytes() {
		if(this.bytes == null) {
			try(InputStream is = this.inputStream) {
				this.bytes = IOUtils.toByteArray(is);
			} catch(IOException e) {
				log.error("", e);
			}
		}
		return this.bytes;
	}
}
